/*
 * @Descripttion: 用户部分vuex
 * @Author: 银河以北
 * @Date: 2021-09-19 17:16:59
 * @LastEditors: 银河以北
 * @LastEditTime: 2021-09-26 09:23:04
 */

import { login, getUserInfo, logout } from "@/api/login/index";

//设置token
import { setToken, removeToken } from '@/utils/auth'
const user = {
    state: {
        //token 
        token: undefined,

        //用户信息
        info: undefined,
    },

    mutations: {
        SET_TOKEN: (state: any, token: string) => {
            state.token = token
        },
        SET_INFO: (state: any, info: object) => {
            state.info = info
        }
    },
    actions: {
        //登录
        Login({ commit }: any, accountData: object) {
            return new Promise((resolve, reject) => {
                login(accountData).then((res: any) => {
                    if (res.code == 200) {
                        const TOKEN = res.data
                        commit('SET_TOKEN', TOKEN)
                        setToken(TOKEN)
                        resolve(res)
                    } else {
                        reject(false)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        GetInfo({ commit }: any) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    if (response) {
                        const result = response.data
                        //在vueX设置用户信息
                        if (result) {
                            commit('SET_INFO', result)
                        } else {
                            reject(new Error('获取用户信息失败!'))
                        }
                        //返回请求信息
                        resolve(response)
                    }

                }).catch(error => {
                    reject(error)
                })
            })
        },
        //退出
        // 用户退出登录
        Logout({ commit, state }: any) {
            return new Promise((resolve) => {
                resolve(true)
                logout().then((res: any) => {
                    if (res.code == 200) {

                        //移除vuex存在的token 个人信息
                        commit('SET_TOKEN', '')
                        commit('SET_INFO', '')

                        //移除本地存储的token
                        removeToken()
                    }
                    resolve(true)
                }).catch(() => {
                    resolve(false)
                })
            })
        }


    }
}
export default user